<template>
  <div class="payment-wrap">
    <!-- 头部导航 -->
    <w-bread-nav title="支付中心"></w-bread-nav>
    <!-- 主内容 -->
    <section class="app-container">
      <div class="payment-price">
        总计商品支付：<span class="c-main">{{orderInfo.PriceAddshipPrice || 0}}</span>元
      </div>
      <dl class="payment-type">
        <dt>请选择支付方式</dt>
        <dd class="select">
          <w-radio v-model="txCode" label="1000" name="txCode" v-if="isTest">
            <i class="ico-nongshanghang"></i>
          </w-radio>
          <w-radio v-model="txCode" label="1312" name="txCode" v-if="isTest">
            <i class="ico-zhongjin"></i>
          </w-radio>
           <w-radio v-model="txCode" label="20" name="txCode" v-if="isTest">
            <i class="ico-zhifubao"></i>
          </w-radio>
          <w-radio v-model="txCode" label="10" name="txCode" v-if="isTest">
            <i class="ico-weixin"></i>
          </w-radio>
          <!-- 微信支付（原生） -->
          <!-- <w-radio v-model="txCode" label="40" name="txCode"  v-if="!isTest">
            <i class="ico-weixin"></i>
          </w-radio> -->
          <!-- 支付宝（原生） -->
          <!-- <w-radio v-model="txCode" label="50" name="txCode" v-if="!isTest">
            <i class="ico-zhifubao"></i>
          </w-radio> -->
          <w-radio v-model="txCode" label="30" name="txCode">
            <i class="icon_daikuan"></i>
          </w-radio>
        </dd>
        <dd class="btn-group">
          <w-button type="main" @on-click="onPayment">下一步</w-button>
        </dd>
      </dl>
      <!-- 规则信息 -->
      <div class="rule-container" v-show="showRule">
        <div class="rule-list">
          <div class="title" v-text="article.title"><i class="iconfont ico-close" @click="showRule = false"></i></div>
          <div class="content" v-html="article.content">{{article.content}}</div>
          <div class="group">
            <w-button class="cancel" @on-click="showRule = false">取消</w-button>
            <w-button class="main" @on-click="tofinanceLoanPage()">确定</w-button>
          </div>
        </div>
        <div class="mark"></div>
      </div>
    </section>
    <!-- 当订单支付成功时，发送表单数据（中金支付） -->
    <form id="payForm" name="payForm" :action="paymentInfo.action" method="post" v-if="paymentInfo.action" target="_blank">
      <input type="hidden" name="message" :value="paymentInfo.message"> 
      <input type="hidden" name="signature" :value="paymentInfo.signature">
      <input type="hidden" name="txCode" :value="paymentInfo.txCode">
    </form>
    <!-- 当订单支付成功时，发送表单数据（农商行支付） -->
    <form id="RCBPayForm" name="RCBPayForm" :action="action" method="post" target="_blank">
      <input type="hidden" name="TransId" value="IPER"> 
      <input type="hidden" name="Plain" :value="rcbPaymentInfo.plain">
      <input type="hidden" name="Signature" :value="rcbPaymentInfo.signData">
    </form>
    <!-- 支付结果弹框 -->
    <!-- <div class="g-pay-result-pop" v-if="isPayResultPop">
      <div class="pay-result-pop">
        <div class="hd clearfix">
          <span class="tit fl">付款遇到问题？</span>  
          <i class="fr iconfont ico-close" @click="onPayError(1)"></i>  
        </div>
        <div class="bd">
          <p class="ct">付款完成前请不要关闭此窗口。完成付款后请根据情况点击下面按钮：</p>
        </div>
        <div class="ft">
          <w-button type="default" @on-click="onPayError(1)">支付遇到问题</w-button>
          <w-button type="main" @on-click="onPaySuccess(1)">已完成付款</w-button>
        </div>
      </div>
    </div> -->
    <!-- <div class="g-pay-result-pop" v-if="isA">
      <div class="pay-result-pop">
        <div class="hd clearfix">
          <span class="tit fl">付款遇到问题？</span>  
          <i class="fr iconfont ico-close" @click="onPayError(2)"></i>  
        </div>
        <div class="bd">
          <p class="ct">该商户没有注册农商行二级商户</p>
        </div>
        <div class="ft">
          <w-button type="default" @on-click="onPayError(2)">取消</w-button>
          <w-button type="main" @on-click="onPaySuccess(2)">前往注册</w-button>
        </div>
      </div>
    </div> -->
    <div v-html="data.orderString" id="formID">
      {{data.orderString}}
    </div>
  </div>
</template>

<script>
  import { apiOrderByIds, apiPayment, apiGetArticle, apiApplyOrderFormPay, apiRCBPayment } from 'js/api'
  import { NSH_URL } from 'js/config'
  import { mapGetters } from 'vuex'
  import { openWindow } from 'js/util'

  // 支付错误提示
  const PAY_ERROR_MSG = {
    'GOODS_IN_STORE': '该商品已下架，不可购买',
    'PAY_SUCCESS': '该订单已支付成功！',
    'NO_PAY_BY_BIC': '该商品暂不支持农商行支付'
  }
  export default {
    data() {
      return {
        txCode: '1312',
        action: NSH_URL, // 9080
        ids: this.$route.query.ids,
        orderInfo: {},
        paymentInfo: {},
        rcbPaymentInfo: {},
        firstClicked: true,
        showRule: false,
        article: '',
        isPayResultPop: false,
        data: {},
        isTest: true, // 测试专用
        isA: false,
        payCode: '', // 支付code码
        timer: '', // 定时器
        orderStatus: ''
      }
    },
    created() {
      // 测试专用
      if (decodeURIComponent(this.$route.query.test || '') == 'zhongjin') {
        this.isTest = false
      }

      // 判断订单Id是否存在，存在请求总价，否则返回上一级
      if (this.ids) {
        // 请求订单数据
        apiOrderByIds(this.$store.getters.token, this.ids).then((data) => {
          this.orderInfo = data

          // 加载中金支付的接口数据
          this.getPaymentInfo(true)

          // // 获取农商行支付信息
          this.getRCBPaymentInfo()
        })
        return
      }

      this.$toast('订单不存在，请重新选择商品', () => {})
    },
    mounted() {
      clearInterval(this.timer)
      /**
       * 定时请求接口，查询当前订单状态
       */
      this.timer = setInterval(() => {
        apiOrderByIds(this.$store.getters.token, this.ids).then((data) => {
          this.orderStatus = data.orderFormList[0].orderStatus
          if (this.orderStatus == '20') {
            clearInterval(this.timer)
            this.$router.push(`/my/order`)
          }
        })
      }, 10000)
    },
    methods: {
      /**
       * 支付失败
       */
      onPayError(id) {
        if (id == 1) {
          this.isPayResultPop = false
        } else if (id == 2) {
          // 若是农商行付款，则支付失败的时候，点击取消时，只关闭当前弹框
          this.isA = false
          // this.$router.back(-1)
        }
      },

      /**
       * 支付成功
       */
      onPaySuccess(id) {
        if (id == 1) {
          this.$router.push('/my/order')
        } else if (id == 2) {
          window.open('/pay/shanghu')
          this.$router.back(-1)
        }
      },

      /**
       * 点击了去支付（下一步）按钮
       */
      onPayment() {
        // 商品已下架，不可支付
        if (this.payCode == '2001') {
          this.$toast(PAY_ERROR_MSG.GOODS_IN_STORE)
          return
        }
        // 支付已完成，不可重复支付
        if (this.payCode == '4011' || this.rcbPaymentInfo == '4011') {
          this.$toast(PAY_ERROR_MSG.PAY_SUCCESS)
          return
        }
        // 如果是金融贷款
        if (this.txCode == 30) {
          this.getArticle()
          return
        }
        // 如果当前是微信支付
        if (this.txCode == 40) {
          this.getWeixin('wxpay')
          return
        }
        // 如果当前是原生支付宝支付
        if (this.txCode == 50) {
          this.getWeixin('alipay')
          return
        }
        // 如果当前是中金支付
        if (this.txCode == 1312) {
          // this.getPaymentInfo()
          // 提交form表单数据
          document.payForm.submit()
          return
        }
        // 如果是农商行支付
        if (this.txCode == 1000) {
          // 农商行支付之前再次调取接口
          this.getRCBPaymentInfo()
          // 用户未注册农商行，则不支持支付
          if (this.rcbPaymentInfo == '8000') {
            this.$toast(PAY_ERROR_MSG.NO_PAY_BY_BIC)
            // this.isA = true
            return
          }
          // 提交form表单数据
          document.RCBPayForm.submit()
          return
        }
        // 去支付（如果是中金支付的支付宝，微信等直接支付）
        this.getPaymentInfo()
      },

      /**
       * 获取支付信息（刚进入此页面的时候加载中金支付的接口），如果是中金的微信和支付宝，则直接打开支付页面
       *
       * @param { Boolean } isFirstIn 第一次进入
       * isFirstIn = false
       */
      getPaymentInfo() {
        // 支付方式编码（1312：中金支付）
        const txCode = this.txCode == '1312' ? '1312' : '1401'
        const paymentWay = this.txCode == '1312' ? null : this.txCode

        // 调用获取支付信息接口，拉起支付页面
        apiPayment(this.token, this.orderInfo.orderformMainId, txCode, paymentWay).then(data => {
          if (data == '2001' || data == '4011') {
            this.payCode = data
            return
          }
          // 微信支付宝支付
          if (data.imageUrl) {
            // 截取二维码数据信息
            // let qrLink = decodeURIComponent(data.imageUrl.split('uuid=')[1])
            // 根据://分割二维码链接
            // let qr = qrLink.split('://')
            this.$toast('正在提交支付', () => {
              // 解决360拦截，将二维码生成链接放置session中
              sessionStorage.setItem('link', data.imageUrl)
              this.$router.push(`/qrCode?ids=${this.ids}`)
              // window.open(`/qrCode?ids=${this.ids}`)
              // this.isPayResultPop = true
            })
          }

          // 中金支付
          if (!data.imageUrl) {
            this.paymentInfo = data
          }
        })
      },

      /**
       * 获取农商行支付的信息（刚进入此页面的时候加载）
       */
      getRCBPaymentInfo() {
        // 调用接口获取信息
        // window.open('')
        apiRCBPayment(this.token, this.orderInfo.orderformMainId).then(data => {
          this.rcbPaymentInfo = data
          // if (data == '8000' && this.txCode == 1000) {
          //   // tempwindow.location = 'http://60.190.244.46:8003/MerPlatForm/mer/index.html?mernbr=20171211151200&merplatformnbr=3G#/doAcctMgm'
          //   // var a = document.createElement('a')
          //   // a.setAttribute('href', '/pay/weixin')
          //   // a.setAttribute('target', '_blank')
          //   // a.setAttribute('id', 'camnpr')
          //   // document.body.appendChild(a)
          //   // a.click()
          //   // window.open('/pay/weixin')
          //   this.isA = true
          // }
        })
      },
      /**
       * 获取贷款须知软文
       */
      getArticle() {
        apiGetArticle().then((data) => {
          this.article = data
          this.showRule = true
        })
      },
      getWeixin(type) {
        apiApplyOrderFormPay({ accessToken: this.$store.getters.token, type: type, id: this.orderInfo.orderformMainId }).then((data) => {
          localStorage.setItem('url', data.code_url)
          localStorage.setItem('userInfo', JSON.stringify(this.$store.getters.userInfo))
          if (type == 'wxpay') {
            this.isPayResultPop = true
            openWindow(`/pay/weixin`)
          } else {
            this.data = data
            setTimeout(() => {
              $(document.getElementsByTagName('form')[0]).submit()
            }, 50)
            this.$spin.show()
          }
          setTimeout(() => {
            this.$spin.close()
          }, 3000)
        })
      },
      /**
       * 跳转到金融贷款页面
       */
      tofinanceLoanPage() {
        // 跳转到申请贷款页面
        // this.$router.push(`/loan/apply/${this.orderInfo.PriceAddshipPrice}/${this.orderInfo.mainOrder_id}`)
        this.$router.push(`/loan/apply/${this.orderInfo.PriceAddshipPrice}/${this.orderInfo.mainOrder_id}/${this.orderInfo.orderformMainId}`)
      }
    },
    computed: {
      ...mapGetters(['token'])
    },
    destroyed() {
      clearInterval(this.timer)
    }
  }
</script>

<style lang="scss" scoped>
@import '../scss/_var.scss';
.app-container {
  position: relative;

  .group {
    text-align: right;
    .cancel {
      background-color: #dddddd;
      margin-right: 40px;
      width: 140px;
      height: 26px;
    }
    .main {
      width: 140px;
      height: 26px;
    }
  }

  .payment-price {
    height: 100px;
    margin-top: 22px;
    line-height: 100px;
    font-size: 18px;
    text-align: center;
    border-bottom: 1px solid #f6f6f6;
    background: $color-white;
  }
  .payment-type {
    background: $color-white;
    dt {
      height: 76px;
      line-height: 76px;
      text-indent: 20px;
      font-size: 16px;
    }
    .select {
      margin-top: 10px;
      padding-bottom: 74px;
      border-bottom: 1px solid #f6f6f6;
      text-align: center;
      label {
        margin-right: 100px;
        &:last-child {
          margin-right: 0;
        }
      }
      i {
        display: inline-block;
        width: 83px;
        height: 83px;
        vertical-align: middle;
      }
      .ico-zhongjin {
        background-image: url('../assets/payment/zhongjin.png');
      }
      .ico-zhifubao {
        background-image: url('../assets/payment/zhifubao.png');
      }
      .ico-weixin {
        background-image: url('../assets/payment/weixin.png');
      }
      .ico-yinlian {
        background-image: url('../assets/payment/yinlian.png');
      }
      .icon_daikuan {
        background-image: url('../assets/payment/icon_daikuan.png');
      }
      .ico-nongshanghang {
        background: url('../assets/payment/nsh.jpg') no-repeat;
        background-size: contain;
      }
    }
    .btn-group {
      padding: 20px 40px 30px 0;
      text-align: right;
      .main {
        width: 180px;
      }
    }
  }
  .rule-list {
    background-color: #FFFFFF;
    color: #666666;
    width: 700px;
    height: 360px;
    padding: 0px 30px;
    position: absolute;
    top: 52px;
    left: 332px;
    z-index: 10;

    .title {
      border-bottom: 1px solid #666666;
      font-size: 14px;
      height: 46px;
      padding: 20px 0px 10px 0px;
      text-align: center;

      .iconfont {
        cursor: pointer;
        float: right;
      }
    }

    .content {
      font-size: 12px;
      line-height: 22px;
      height: 260px;
      overflow: auto;
      padding-top: 20px;
    }
  }
  .mark {
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    z-index: 5;
  }
}
.g-pay-result-pop {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, .3);
  }
  .pay-result-pop {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 550px;
    height: 190px;
    margin-left: -275px;
    margin-top: -95px;
    padding: 20px 38px;
    background: #fff;
    color: #666;
    .hd {
      padding: 10px 0;
      border-bottom: 1px solid #ddd;
      .tit {
        font-size: 16px;
      }
      .ico-close {
        cursor: pointer;
      }
    }
    .bd {
      padding: 20px 0;
    }
    .ft {
      padding-top: 20px;
      text-align: center;
      .default {
        margin-right: 38px;
      }
      .btn {
        height: 28px;
      }
    }
  }
</style>